// puzzle.js - 添加体力恢复时间显示
import EnergyManager from './energyManager.js';

export default class PuzzleGame {
  constructor(canvas, context) {
    this.canvas = canvas;
    this.ctx = context;
    this.image = null;

    // 游戏配置
    this.gridSize = 3;
    this.tileSize = 0;
    this.tiles = [];
    this.emptyPosition = {
      row: 2,
      col: 2
    };
    this.steps = 0;
    this.gameStarted = false;

    // 时间系统
    this.timeLimit = 0; // 时间限制（秒）
    this.remainingTime = 0; // 剩余时间
    this.timerInterval = null; // 计时器
    this.startTime = 0; // 游戏开始时间
    this.isTimerPaused = false; // 新增：计时器暂停状态

    // 体力系统
    this.energyManager = new EnergyManager();

    // 拖动相关
    this.draggingTile = null;
    this.dragStartX = 0;
    this.dragStartY = 0;
    this.dragOffsetX = 0;
    this.dragOffsetY = 0;
    this.originalPosition = {
      row: 0,
      col: 0
    };

    // 拼图区域
    this.puzzleX = 0;
    this.puzzleY = 0;
    this.puzzleWidth = 0;
    this.puzzleHeight = 0;

    // 屏幕信息
    this.screenWidth = 0;
    this.screenHeight = 0;

    // UI 颜色主题
    this.colors = {
      primary: '#6366F1', // 主色调 - 靛蓝色
      primaryDark: '#4F46E5', // 深主色
      secondary: '#10B981', // 次要色 - 翠绿色
      secondaryDark: '#059669', // 深次要色
      background: '#F8FAFC', // 背景色 - 浅灰蓝
      surface: '#FFFFFF', // 表面色 - 白色
      text: '#1E293B', // 文字色 - 深灰蓝
      textLight: '#64748B', // 浅文字色
      border: '#E2E8F0', // 边框色
      shadow: 'rgba(0, 0, 0, 0.1)' // 阴影
    };

    // 难度对应的时间限制（秒）
    this.difficultyTimeLimits = {
      3: 180, // 3×3 - 3分钟
      4: 300, // 4×4 - 5分钟
      5: 480 // 5×5 - 8分钟
    };
  }

  setImage(image) {
    this.image = image;
    this.calculateLayout();
  }

  calculateLayout() {
    // 获取屏幕尺寸和安全区域
    const systemInfo = wx.getSystemInfoSync();
    this.screenWidth = systemInfo.windowWidth;
    this.screenHeight = systemInfo.windowHeight;

    console.log('屏幕尺寸:', this.screenWidth, 'x', this.screenHeight);
    console.log('安全区域:', systemInfo.safeArea);

    // 设置边距为10像素
    const margin = 10;

    // 使用安全区域信息
    const safeArea = systemInfo.safeArea;
    const safeAreaTop = safeArea.top;

    // 胶囊按钮高度
    const capsuleHeight = 32;

    // 按钮高度
    const buttonHeight = Math.max(25, this.screenWidth * 0.07);

    // UI区域高度 (安全区域 + 胶囊按钮高度 + 按钮高度 + 20像素间距)
    const uiHeight = safeAreaTop + capsuleHeight + buttonHeight + 20 + 20;

    // 计算可用拼图区域 (屏幕宽度减去左右各10像素边距)
    const maxPuzzleWidth = this.screenWidth - margin * 2;

    // 底部安全区域
    const bottomSafeArea = Math.max(10, this.screenHeight * 0.02);
    const maxPuzzleHeight = this.screenHeight - uiHeight - bottomSafeArea;

    // 直接使用最大可用宽度作为拼图区域宽度
    this.puzzleWidth = maxPuzzleWidth;

    // 根据图片比例计算高度
    if (this.image) {
      const imageRatio = this.image.width / this.image.height;
      this.puzzleHeight = this.puzzleWidth / imageRatio;
    } else {
      this.puzzleHeight = this.puzzleWidth; // 如果没有图片，使用正方形
    }

    // 确保高度不会超出可用区域
    if (this.puzzleHeight > maxPuzzleHeight) {
      const heightScale = maxPuzzleHeight / this.puzzleHeight;
      this.puzzleHeight = maxPuzzleHeight;
      this.puzzleWidth *= heightScale;
    }

    // 计算拼图块大小
    this.tileSize = this.puzzleWidth / this.gridSize;

    // 设置拼图位置 - 水平使用10像素边距，垂直考虑安全区域和UI区域
    this.puzzleX = margin; // 左边距10像素
    this.puzzleY = uiHeight + 100; // 在UI区域下方

    console.log('最终拼图区域:', this.puzzleWidth, 'x', this.puzzleHeight);
    console.log('最终拼图位置:', this.puzzleX, this.puzzleY);
    console.log('最终拼图块大小:', this.tileSize);

    // 检查拼图块是否过小
    const minTileSize = 40; // 最小拼图块尺寸
    if (this.tileSize < minTileSize) {
      console.warn('拼图块可能过小，考虑降低难度');
      // 如果拼图块太小，调整拼图区域大小
      this.puzzleWidth = minTileSize * this.gridSize;
      this.tileSize = minTileSize;

      if (this.image) {
        const imageRatio = this.image.width / this.image.height;
        this.puzzleHeight = this.puzzleWidth / imageRatio;
      } else {
        this.puzzleHeight = this.puzzleWidth;
      }

      // 重新计算位置
      this.puzzleX = (this.screenWidth - this.puzzleWidth) / 2;
    }
  }

  // 设置时间限制基于难度
  setTimeLimitByDifficulty() {
    this.timeLimit = this.difficultyTimeLimits[this.gridSize] || 180;
    this.remainingTime = this.timeLimit;
  }

  // 修改 start 方法，重置暂停状态
  start() {
    // 检查体力
    if (!this.energyManager.canStartGame()) {
      this.showNoEnergyDialog();
      return;
    }

    // 消耗体力
    if (!this.energyManager.consumeEnergy()) {
      this.showNoEnergyDialog();
      return;
    }

    // 设置时间限制
    this.setTimeLimitByDifficulty();

    // 重置暂停状态
    this.isTimerPaused = false;

    // 准备游戏
    this.prepareTiles();
    this.shuffleTiles();
    this.gameStarted = true;
    this.steps = 0;

    // 开始计时
    this.startTimer();

    // 绘制界面
    this.draw();

    console.log(`开始游戏，难度: ${this.gridSize}×${this.gridSize}, 时间限制: ${this.timeLimit}秒`);
  }

  // 开始计时器
  startTimer() {
    this.startTime = Date.now();

    // 清除之前的计时器
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }

    // 每秒更新一次时间
    this.timerInterval = setInterval(() => {
      this.updateTimer();
    }, 1000);
  }

  // 修改 updateTimer 方法，考虑暂停状态
  updateTimer() {
    if (!this.gameStarted || this.isTimerPaused) return;

    const elapsed = Math.floor((Date.now() - this.startTime) / 1000);
    this.remainingTime = Math.max(0, this.timeLimit - elapsed);

    // 时间到，游戏结束
    if (this.remainingTime <= 0) {
      this.gameOver('timeout');
    } else {
      // 重绘界面更新时间显示
      this.draw();
    }
  }

  // 修改 gameOver 方法，重置暂停状态
  gameOver(reason) {
    // 停止计时器
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
      this.timerInterval = null;
    }

    // 重置暂停状态
    this.isTimerPaused = false;

    this.gameStarted = false;

    // 显示游戏结束对话框
    if (reason === 'timeout') {
      this.showTimeOutDialog();
    } else if (reason === 'success') {
      // 成功完成的处理在原有逻辑中
    }
  }

  // 显示时间到对话框
  showTimeOutDialog() {
    wx.showModal({
      title: '时间到！',
      content: `很遗憾，时间到了！\n你已经完成了 ${this.getCompletionPercent()}%`,
      confirmText: '再试一次',
      cancelText: '返回菜单',
      success: (res) => {
        if (res.confirm) {
          this.start(); // 重新开始
        } else {
          this.backToMenu();
        }
      }
    });
  }

  prepareTiles() {
    this.tiles = [];

    // 根据网格大小设置空白块位置
    this.emptyPosition = {
      row: this.gridSize - 1,
      col: this.gridSize - 1
    };

    for (let row = 0; row < this.gridSize; row++) {
      for (let col = 0; col < this.gridSize; col++) {
        // 跳过空白块
        if (row === this.emptyPosition.row && col === this.emptyPosition.col) {
          continue;
        }

        this.tiles.push({
          correctRow: row,
          correctCol: col,
          currentRow: row,
          currentCol: col,
          isEmpty: false
        });
      }
    }

    console.log(`初始化 ${this.gridSize}x${this.gridSize} 拼图块:`, this.tiles.length, '个');
  }

  shuffleTiles() {
    // 简单打乱：执行随机移动
    for (let i = 0; i < 100; i++) {
      const movableTiles = this.getMovableTiles();
      if (movableTiles.length > 0) {
        const randomTile = movableTiles[Math.floor(Math.random() * movableTiles.length)];
        this.moveTileToEmpty(randomTile);
      }
    }
    this.steps = 0;
  }

  getMovableTiles() {
    const movableTiles = [];
    const {
      row: emptyRow,
      col: emptyCol
    } = this.emptyPosition;

    // 检查上下左右四个方向
    const directions = [{
        dr: -1,
        dc: 0
      }, // 上
      {
        dr: 1,
        dc: 0
      }, // 下
      {
        dr: 0,
        dc: -1
      }, // 左
      {
        dr: 0,
        dc: 1
      } // 右
    ];

    for (const dir of directions) {
      const adjacentRow = emptyRow + dir.dr;
      const adjacentCol = emptyCol + dir.dc;

      if (this.isValidPosition(adjacentRow, adjacentCol)) {
        const tile = this.getTileAt(adjacentRow, adjacentCol);
        if (tile) {
          movableTiles.push(tile);
        }
      }
    }

    return movableTiles;
  }

  isValidPosition(row, col) {
    return row >= 0 && row < this.gridSize && col >= 0 && col < this.gridSize;
  }

  getTileAt(row, col) {
    return this.tiles.find(tile =>
      tile.currentRow === row && tile.currentCol === col && !tile.isEmpty
    );
  }

  moveTileToEmpty(tile) {
    if (!this.canMove(tile)) {
      console.log('不能移动这个拼图块');
      return false;
    }

    // 交换位置
    const tempRow = tile.currentRow;
    const tempCol = tile.currentCol;

    tile.currentRow = this.emptyPosition.row;
    tile.currentCol = this.emptyPosition.col;

    this.emptyPosition.row = tempRow;
    this.emptyPosition.col = tempCol;

    this.steps++;
    return true;
  }

  canMove(tile) {
    const {
      row: emptyRow,
      col: emptyCol
    } = this.emptyPosition;
    const rowDiff = Math.abs(tile.currentRow - emptyRow);
    const colDiff = Math.abs(tile.currentCol - emptyCol);

    // 相邻的条件：行差和列差之和为1（即上下左右相邻）
    return (rowDiff === 1 && colDiff === 0) || (rowDiff === 0 && colDiff === 1);
  }

  // 修改 onTouchStart 方法，确保在游戏未开始时不会处理触摸
  onTouchStart(touch) {
    if (!this.gameStarted) {
      console.log('游戏未开始，忽略触摸');
      return;
    }

    // 检查按钮点击
    if (this.checkButtonClick(touch.clientX, touch.clientY)) {
      return;
    }

    // 转换为拼图区域内的相对坐标
    const relativeX = touch.clientX - this.puzzleX;
    const relativeY = touch.clientY - this.puzzleY;

    // 检查是否在拼图区域内
    if (relativeX < 0 || relativeY < 0 ||
      relativeX > this.puzzleWidth || relativeY > this.puzzleHeight) {
      return;
    }

    // 计算点击的拼图块坐标
    const col = Math.floor(relativeX / this.tileSize);
    const row = Math.floor(relativeY / this.tileSize);

    console.log(`触摸开始: 屏幕(${touch.clientX}, ${touch.clientY}) -> 相对(${relativeX}, ${relativeY}) -> 拼图块(${row}, ${col})`);

    // 检查是否点击了空白块
    if (row === this.emptyPosition.row && col === this.emptyPosition.col) {
      console.log('点击了空白块');
      return;
    }

    // 获取点击的拼图块
    this.draggingTile = this.getTileAt(row, col);

    if (this.draggingTile) {
      console.log('开始拖动拼图块:', this.draggingTile);

      // 记录拖动起始位置
      this.dragStartX = touch.clientX;
      this.dragStartY = touch.clientY;
      this.dragOffsetX = 0;
      this.dragOffsetY = 0;

      // 记录原始位置
      this.originalPosition.row = this.draggingTile.currentRow;
      this.originalPosition.col = this.draggingTile.currentCol;

      // 立即重绘，显示拖动效果
      this.draw();
    }
  }

  onTouchMove(touch) {
    if (!this.gameStarted || !this.draggingTile) return;

    // 计算拖动偏移量
    this.dragOffsetX = touch.clientX - this.dragStartX;
    this.dragOffsetY = touch.clientY - this.dragStartY;

    console.log(`拖动中: 偏移(${this.dragOffsetX}, ${this.dragOffsetY})`);

    // 重绘画布，显示拖动效果
    this.draw();
  }

  tryMoveSelectedTile() {
    if (!this.selectedTile) return;

    if (this.canMove(this.selectedTile)) {
      console.log('可以移动，执行移动');
      this.moveTileToEmpty(this.selectedTile);
      this.draw();

      // 检查是否完成
      if (this.checkCompletion()) {
        setTimeout(() => {
          this.showSuccess();
        }, 300);
      }
    } else {
      console.log('选中的拼图块不能移动');
      // 给用户视觉反馈
      this.highlightTile(this.selectedTile);
    }

    this.selectedTile = null;
  }

  highlightTile(tile) {
    const x = this.puzzleX + tile.currentCol * this.tileSize;
    const y = this.puzzleY + tile.currentRow * this.tileSize;

    this.ctx.strokeStyle = '#FF0000';
    this.ctx.lineWidth = 3;
    this.ctx.strokeRect(x, y, this.tileSize, this.tileSize);

    // 短暂延迟后重绘
    setTimeout(() => {
      this.draw();
    }, 200);
  }

  onTouchEnd(touch) {
    if (!this.gameStarted || !this.draggingTile) {
      this.draggingTile = null;
      return;
    }

    console.log(`触摸结束: 最终偏移(${this.dragOffsetX}, ${this.dragOffsetY})`);

    // 计算拖动距离
    const dragDistance = Math.sqrt(this.dragOffsetX * this.dragOffsetX + this.dragOffsetY * this.dragOffsetY);
    const minDragDistance = this.tileSize * 0.3; // 最小拖动距离为拼图块大小的30%

    console.log(`拖动距离: ${dragDistance}, 最小要求: ${minDragDistance}`);

    if (dragDistance < minDragDistance) {
      // 拖动距离太小，视为点击，不进行交换
      console.log('拖动距离太小，不进行交换');
      this.draggingTile = null;
      this.draw();
      return;
    }

    // 确定拖动方向
    let targetRow = this.originalPosition.row;
    let targetCol = this.originalPosition.col;

    if (Math.abs(this.dragOffsetX) > Math.abs(this.dragOffsetY)) {
      // 水平拖动
      if (this.dragOffsetX > 0) {
        targetCol += 1; // 向右拖动
      } else {
        targetCol -= 1; // 向左拖动
      }
    } else {
      // 垂直拖动
      if (this.dragOffsetY > 0) {
        targetRow += 1; // 向下拖动
      } else {
        targetRow -= 1; // 向上拖动
      }
    }

    console.log(`拖动方向: (${this.dragOffsetX}, ${this.dragOffsetY}) -> 目标位置: (${targetRow}, ${targetCol})`);
    console.log(`空白块位置: (${this.emptyPosition.row}, ${this.emptyPosition.col})`);

    // 检查目标位置是否是空白块
    if (targetRow === this.emptyPosition.row && targetCol === this.emptyPosition.col) {
      console.log('可以移动到空白位置');
      this.moveTileToEmpty(this.draggingTile);
      this.steps++;

      // 检查是否完成
      if (this.checkCompletion()) {
        setTimeout(() => {
          this.showSuccess();
        }, 300);
      }
    } else {
      console.log('目标位置不是空白块，不能移动');
    }

    // 重置拖动状态
    this.draggingTile = null;
    this.dragOffsetX = 0;
    this.dragOffsetY = 0;

    // 重绘画布
    this.draw();
  }

  draw() {
    // 清空画布
    this.ctx.clearRect(0, 0, this.screenWidth, this.screenHeight);

    // 绘制渐变背景
    this.drawBackground();

    // 绘制拼图区域背景 - 带圆角和阴影
    this.drawPuzzleBackground();

    // 绘制顺序调整：
    // 1. 先绘制所有非拖动的拼图块
    for (const tile of this.tiles) {
      if (this.draggingTile !== tile) {
        this.drawStaticTile(tile);
      }
    }

    // 2. 绘制空白块
    this.drawEmptyTile();

    // 3. 最后绘制正在拖动的拼图块（确保在最上层）
    if (this.draggingTile) {
      this.drawDraggingTile(this.draggingTile);
    }

    // 绘制UI
    this.drawUI();
  }

  // 绘制静态（非拖动）的拼图块
  drawStaticTile(tile) {
    const x = Math.round(this.puzzleX + tile.currentCol * this.tileSize);
    const y = Math.round(this.puzzleY + tile.currentRow * this.tileSize);

    this.drawTileImage(tile, x, y);

    // 绘制边框
    this.ctx.strokeStyle = this.colors.border;
    this.ctx.lineWidth = 1;
    this.ctx.strokeRect(x, y, Math.round(this.tileSize), Math.round(this.tileSize));
  }

  // 绘制正在拖动的拼图块
  drawDraggingTile(tile) {
    let x = Math.round(this.puzzleX + tile.currentCol * this.tileSize);
    let y = Math.round(this.puzzleY + tile.currentRow * this.tileSize);

    // 应用拖动偏移量
    x += Math.round(this.dragOffsetX);
    y += Math.round(this.dragOffsetY);

    // 为拖动的拼图块添加阴影
    this.ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
    this.ctx.shadowBlur = 10;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 4;

    // 绘制图片
    this.drawTileImage(tile, x, y);

    // 绘制边框
    this.ctx.strokeStyle = this.colors.primary;
    this.ctx.lineWidth = 2;
    this.ctx.strokeRect(x, y, Math.round(this.tileSize), Math.round(this.tileSize));

    // 添加半透明覆盖层
    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
    this.ctx.fillRect(x, y, Math.round(this.tileSize), Math.round(this.tileSize));

    // 重置阴影
    this.ctx.shadowColor = 'transparent';
    this.ctx.shadowBlur = 0;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;
  }

  // 通用的拼图块图片绘制方法
  drawTileImage(tile, x, y) {
    // 计算源图像中的位置
    const srcX = tile.correctCol * (this.image.width / this.gridSize);
    const srcY = tile.correctRow * (this.image.height / this.gridSize);
    const srcWidth = this.image.width / this.gridSize;
    const srcHeight = this.image.height / this.gridSize;

    // 绘制拼图块图片
    this.ctx.drawImage(
      this.image,
      srcX, srcY, srcWidth, srcHeight,
      x, y, Math.round(this.tileSize), Math.round(this.tileSize)
    );
  }

  // 为了向后兼容，保留原来的 drawTile 方法
  drawTile(tile) {
    const isDragging = this.draggingTile === tile;
    if (isDragging) {
      this.drawDraggingTile(tile);
    } else {
      this.drawStaticTile(tile);
    }
  }

  drawBackground() {
    // 创建渐变背景
    const gradient = this.ctx.createLinearGradient(0, 0, this.screenWidth, this.screenHeight);
    gradient.addColorStop(0, this.colors.background);
    gradient.addColorStop(1, '#F1F5F9');

    this.ctx.fillStyle = gradient;
    this.ctx.fillRect(0, 0, this.screenWidth, this.screenHeight);
  }

  drawPuzzleBackground() {
    const radius = 12; // 圆角半径

    // 绘制阴影
    this.ctx.shadowColor = this.colors.shadow;
    this.ctx.shadowBlur = 15;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 4;

    // 绘制圆角矩形背景
    this.ctx.fillStyle = this.colors.surface;
    this.roundRect(
      this.ctx,
      this.puzzleX - 8,
      this.puzzleY - 8,
      this.puzzleWidth + 16,
      this.puzzleHeight + 16,
      radius
    );
    this.ctx.fill();

    // 重置阴影
    this.ctx.shadowColor = 'transparent';
    this.ctx.shadowBlur = 0;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;
  }

  drawEmptyTile() {
    // 使用整数坐标绘制空白块
    const x = Math.round(this.puzzleX + this.emptyPosition.col * this.tileSize);
    const y = Math.round(this.puzzleY + this.emptyPosition.row * this.tileSize);

    // 绘制空白块背景 - 渐变效果
    const gradient = this.ctx.createLinearGradient(x, y, x + this.tileSize, y + this.tileSize);
    gradient.addColorStop(0, '#F8FAFC');
    gradient.addColorStop(1, '#E2E8F0');

    this.ctx.fillStyle = gradient;
    this.ctx.fillRect(x, y, Math.round(this.tileSize), Math.round(this.tileSize));

    // 绘制边框
    this.ctx.strokeStyle = this.colors.border;
    this.ctx.lineWidth = 1;
    this.ctx.strokeRect(x, y, Math.round(this.tileSize), Math.round(this.tileSize));

    // 绘制提示图标
    this.ctx.fillStyle = this.colors.textLight;
    this.ctx.font = '20px Arial';
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';
    this.ctx.fillText(
      '',
      x + Math.round(this.tileSize / 2),
      y + Math.round(this.tileSize / 2)
    );
    this.ctx.textAlign = 'left';
  }

  // 修改 drawUI 方法中的调用顺序
  drawUI() {
    // 根据屏幕尺寸调整字体大小
    const baseFontSize = Math.max(14, Math.round(this.screenWidth * 0.04));
    const smallFontSize = Math.max(12, Math.round(this.screenWidth * 0.035));

    // 绘制体力显示
    this.drawEnergyDisplay(baseFontSize);

    // 绘制倒计时 - 移到游戏信息上方
    this.drawTimer(baseFontSize);

    // 绘制游戏信息和按钮
    this.drawGameInfoAndButtons(baseFontSize, smallFontSize);
  }

  // 修改 drawTimer 方法，再上移20像素
  drawTimer(baseFontSize) {
    // 获取安全区域信息
    const systemInfo = wx.getSystemInfoSync();
    const safeAreaTop = systemInfo.safeArea.top;
    const capsuleHeight = 32;

    // 倒计时位置 - 再上移20像素
    const timerY = Math.round(safeAreaTop + capsuleHeight + 15); // 从35改为15

    // 时间显示
    const timeText = this.formatTime(this.remainingTime);
    const timeColor = this.remainingTime <= 30 ? '#EF4444' : this.colors.primary;

    // 调整倒计时背景尺寸
    const timerWidth = Math.round(this.screenWidth * 0.22);
    const timerHeight = Math.round(32);
    const timerX = Math.round((this.screenWidth - timerWidth) / 2);

    // 绘制倒计时背景
    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
    this.roundRect(this.ctx, timerX, timerY, timerWidth, timerHeight, 16);
    this.ctx.fill();

    // 添加边框
    this.ctx.strokeStyle = this.remainingTime <= 30 ? '#EF4444' : this.colors.primary;
    this.ctx.lineWidth = 2;
    this.roundRect(this.ctx, timerX, timerY, timerWidth, timerHeight, 16);
    this.ctx.stroke();

    // 绘制倒计时文字
    this.ctx.fillStyle = timeColor;
    this.ctx.font = `bold ${baseFontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    this.ctx.fillText(
      timeText,
      Math.round(this.screenWidth / 2),
      Math.round(timerY + timerHeight / 2)
    );

    // 重置文本对齐
    this.ctx.textAlign = 'left';
    this.ctx.textBaseline = 'alphabetic';
  }

  // 修改 drawGameInfoAndButtons 方法，再上移20像素
  drawGameInfoAndButtons(baseFontSize, smallFontSize) {
    // 获取安全区域信息
    const systemInfo = wx.getSystemInfoSync();
    const safeAreaTop = systemInfo.safeArea.top;
    const capsuleHeight = 32;

    // 调整按钮尺寸
    const buttonHeight = Math.max(32, Math.round(this.screenWidth * 0.08));
    const buttonWidth = Math.max(80, Math.round(this.screenWidth * 0.2));
    const margin = 10;
    const buttonFontSize = Math.max(12, Math.round(this.screenWidth * 0.035));

    // 调整垂直位置 - 再上移20像素
    const infoButtonsY = Math.round(safeAreaTop + capsuleHeight + 55); // 从75改为55

    // 绘制游戏信息 - 放在按钮上方
    this.drawGameInfo(baseFontSize, smallFontSize, infoButtonsY);

    // 绘制按钮 - 放在游戏信息下方
    const buttonsY = infoButtonsY + 45; // 游戏信息高度约40px + 5px间距
    this.drawButtons(buttonHeight, buttonWidth, margin, buttonFontSize, buttonsY);
  }

  // 修改 drawGameInfo 方法，调整位置和样式
  drawGameInfo(baseFontSize, smallFontSize, yPosition) {
    // 调整信息卡片尺寸
    const cardWidth = Math.round(this.screenWidth * 0.32);
    const cardHeight = Math.round(36);
    const cardX = Math.round((this.screenWidth - cardWidth) / 2); // 居中显示
    const cardY = yPosition;

    // 绘制信息卡片背景
    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
    this.roundRect(this.ctx, cardX, cardY, cardWidth, cardHeight, 10);
    this.ctx.fill();

    // 添加边框
    this.ctx.strokeStyle = this.colors.border;
    this.ctx.lineWidth = 1;
    this.roundRect(this.ctx, cardX, cardY, cardWidth, cardHeight, 10);
    this.ctx.stroke();

    // 绘制信息文字 - 调整为单行显示，更紧凑
    this.ctx.fillStyle = this.colors.text;
    this.ctx.font = `500 ${smallFontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    const textX = cardX + cardWidth / 2;
    const textY = cardY + cardHeight / 2;

    // 步数和难度在一行显示，用 | 分隔
    this.ctx.fillText(`步数:${this.steps} | 难度${this.gridSize}×${this.gridSize}`, textX, textY);
  }

  // 在 drawButtons 方法中修改按钮文字和功能
  drawButtons(buttonHeight, buttonWidth, margin, buttonFontSize, yPosition) {
    // 计算总按钮宽度
    let totalButtons = 2; // 返回和重来按钮
    if (this.gameStarted) totalButtons++; // 加时间按钮
    if (this.energyManager.getCurrentEnergy() === 0) totalButtons++; // 加体力按钮

    const totalWidth = (buttonWidth * totalButtons) + (margin * (totalButtons - 1));
    let currentX = Math.round((this.screenWidth - totalWidth) / 2); // 居中开始

    // 关键修改：当体力不为0时，确保清空广告按钮
    this.watchAdButton = null;
    this.watchAdTimeButton = null;

    // 先绘制加体力按钮（如果需要）
    if (this.energyManager.getCurrentEnergy() === 0) {
      this.watchAdButton = {
        x: currentX,
        y: yPosition,
        width: buttonWidth,
        height: buttonHeight
      };

      // 修改：将"体力+1"改为"体力"
      this.drawModernButton(
        this.watchAdButton.x,
        this.watchAdButton.y,
        this.watchAdButton.width,
        this.watchAdButton.height,
        '体力', // 修改文字
        ['#F59E0B', '#D97706'],
        buttonFontSize
      );

      currentX += buttonWidth + margin;
    }

    // 绘制加时间按钮（如果游戏进行中）
    if (this.gameStarted) {
      this.watchAdTimeButton = {
        x: currentX,
        y: yPosition,
        width: buttonWidth,
        height: buttonHeight
      };

      // 修改：将"+60s"改为"时间"
      this.drawModernButton(
        this.watchAdTimeButton.x,
        this.watchAdTimeButton.y,
        this.watchAdTimeButton.width,
        this.watchAdTimeButton.height,
        '时间', // 修改文字
        ['#8B5CF6', '#7C3AED'],
        buttonFontSize
      );

      currentX += buttonWidth + margin;
    }

    // 重新开始按钮
    this.restartButton = {
      x: currentX,
      y: yPosition,
      width: buttonWidth,
      height: buttonHeight
    };

    // 绘制重新开始按钮
    this.drawModernButton(
      this.restartButton.x,
      this.restartButton.y,
      this.restartButton.width,
      this.restartButton.height,
      '重来-1',
      [this.colors.secondary, this.colors.secondaryDark],
      buttonFontSize
    );

    currentX += buttonWidth + margin;

    // 返回菜单按钮
    this.backButton = {
      x: currentX,
      y: yPosition,
      width: buttonWidth,
      height: buttonHeight
    };

    // 绘制返回按钮
    this.drawModernButton(
      this.backButton.x,
      this.backButton.y,
      this.backButton.width,
      this.backButton.height,
      '返回',
      [this.colors.primary, this.colors.primaryDark],
      buttonFontSize
    );
  }


  // 修改 drawEnergyDisplay 方法，使其可点击
  drawEnergyDisplay(baseFontSize) {
    const systemInfo = wx.getSystemInfoSync();
    const safeAreaTop = systemInfo.safeArea.top;
    const capsuleHeight = 32;
    const margin = 12;

    // 调整体力显示尺寸
    const energyWidth = Math.round(this.screenWidth * 0.16);
    const energyHeight = Math.round(40);
    const energyX = margin;
    const energyY = Math.round(safeAreaTop + capsuleHeight + margin);

    // 记录体力显示区域，用于点击检测
    this.energyDisplayArea = {
      x: energyX,
      y: energyY,
      width: energyWidth,
      height: energyHeight
    };

    // 获取体力信息
    const currentEnergy = this.energyManager.getCurrentEnergy();
    const timeToNextRecovery = this.energyManager.getTimeToNextRecovery();
    const recoveryProgress = this.energyManager.getRecoveryProgress();

    // 调整进度条尺寸
    const barWidth = 5;
    const barHeight = energyHeight - 12;
    const barX = energyX;
    const barY = energyY + 6;

    // 绘制垂直进度条背景
    this.ctx.fillStyle = '#E2E8F0';
    this.roundRect(this.ctx, barX, barY, barWidth, barHeight, 3);
    this.ctx.fill();

    // 绘制垂直进度条前景（体力值）
    const energyPercent = this.energyManager.getEnergyPercent();
    const energyHeightFill = Math.max(4, barHeight * energyPercent);

    // 根据体力值改变颜色
    let energyColor;
    if (energyPercent > 0.6) {
      energyColor = '#10B981';
    } else if (energyPercent > 0.3) {
      energyColor = '#F59E0B';
    } else {
      energyColor = '#EF4444';
    }

    this.ctx.fillStyle = energyColor;
    this.roundRect(this.ctx, barX, barY + barHeight - energyHeightFill, barWidth, energyHeightFill, 3);
    this.ctx.fill();

    // 绘制恢复进度条（如果体力未满）
    if (currentEnergy < this.energyManager.maxEnergy && timeToNextRecovery > 0) {
      const recoveryHeightFill = Math.max(4, barHeight * recoveryProgress);

      this.ctx.fillStyle = 'rgba(99, 102, 241, 0.3)';
      this.roundRect(this.ctx, barX, barY + barHeight - recoveryHeightFill, barWidth, recoveryHeightFill, 3);
      this.ctx.fill();
    }

    // 绘制体力数值和恢复时间
    this.ctx.fillStyle = this.colors.text;
    this.ctx.font = `500 ${Math.max(10, baseFontSize - 3)}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'left';

    // 体力数值
    this.ctx.fillText(
      `${currentEnergy}/${this.energyManager.maxEnergy}`,
      energyX + barWidth + 6,
      energyY + 16
    );

    // 如果体力未满，显示恢复时间
    if (currentEnergy < this.energyManager.maxEnergy && timeToNextRecovery > 0) {
      const recoveryTime = this.energyManager.formatRecoveryTime(timeToNextRecovery);
      const timeFontSize = Math.max(8, Math.round(this.screenWidth * 0.022));

      this.ctx.fillStyle = this.colors.textLight;
      this.ctx.font = `${timeFontSize}px "Helvetica Neue", Arial, sans-serif`;

      this.ctx.fillText(
        recoveryTime,
        energyX + barWidth + 6,
        energyY + 30
      );
    }
  }

  // 修改 drawModernButton 方法，让按钮更紧凑
  drawModernButton(x, y, width, height, text, gradientColors, fontSize) {
    const radius = 8; // 减小圆角半径

    // 绘制阴影
    this.ctx.shadowColor = 'rgba(0, 0, 0, 0.12)';
    this.ctx.shadowBlur = 6;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 2;

    // 绘制渐变背景
    const gradient = this.ctx.createLinearGradient(x, y, x, y + height);
    gradient.addColorStop(0, gradientColors[0]);
    gradient.addColorStop(1, gradientColors[1]);

    this.ctx.fillStyle = gradient;
    this.roundRect(this.ctx, x, y, width, height, radius);
    this.ctx.fill();

    // 重置阴影
    this.ctx.shadowColor = 'transparent';
    this.ctx.shadowBlur = 0;
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;

    // 绘制按钮文字
    this.ctx.fillStyle = '#FFFFFF';
    this.ctx.font = `bold ${fontSize}px "Helvetica Neue", Arial, sans-serif`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    this.ctx.fillText(
      text,
      Math.round(x + width / 2),
      Math.round(y + height / 2)
    );

    // 重置文本设置
    this.ctx.textAlign = 'left';
    this.ctx.textBaseline = 'alphabetic';
  }

  // 绘制圆角矩形工具函数
  roundRect(ctx, x, y, width, height, radius) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.lineTo(x + width - radius, y);
    ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
    ctx.lineTo(x + width, y + height - radius);
    ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
    ctx.lineTo(x + radius, y + height);
    ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
    ctx.lineTo(x, y + radius);
    ctx.quadraticCurveTo(x, y, x + radius, y);
    ctx.closePath();
  }

  // 修改 checkButtonClick 方法中的按钮处理
  checkButtonClick(x, y) {
    // 检查体力显示区域点击
    if (this.energyDisplayArea &&
      x >= this.energyDisplayArea.x && x <= this.energyDisplayArea.x + this.energyDisplayArea.width &&
      y >= this.energyDisplayArea.y && y <= this.energyDisplayArea.y + this.energyDisplayArea.height) {
      console.log('点击体力显示区域');
      this.showEnergyDialog();
      return true;
    }

    // 检查返回按钮
    if (this.backButton &&
      x >= this.backButton.x && x <= this.backButton.x + this.backButton.width &&
      y >= this.backButton.y && y <= this.backButton.y + this.backButton.height) {
      console.log('点击返回按钮');
      this.backToMenu();
      return true;
    }

    // 检查重新开始按钮
    if (this.restartButton &&
      x >= this.restartButton.x && x <= this.restartButton.x + this.restartButton.width &&
      y >= this.restartButton.y && y <= this.restartButton.y + this.restartButton.height) {
      console.log('点击重新开始按钮');
      this.restart();
      return true;
    }

    // 检查体力按钮 - 修改为弹出选择对话框
    if (this.watchAdButton &&
      x >= this.watchAdButton.x && x <= this.watchAdButton.x + this.watchAdButton.width &&
      y >= this.watchAdButton.y && y <= this.watchAdButton.y + this.watchAdButton.height) {
      console.log('点击体力按钮');
      this.showEnergyAcquisitionDialog(); // 新增方法
      return true;
    }

    // 检查时间按钮 - 修改为弹出选择对话框
    if (this.watchAdTimeButton &&
      x >= this.watchAdTimeButton.x && x <= this.watchAdTimeButton.x + this.watchAdTimeButton.width &&
      y >= this.watchAdTimeButton.y && y <= this.watchAdTimeButton.y + this.watchAdTimeButton.height) {
      console.log('点击时间按钮');
      this.showTimeAcquisitionDialog(); // 新增方法
      return true;
    }

    return false;
  }

  // 新增：体力获取选择对话框
  showEnergyAcquisitionDialog() {
    wx.showModal({
      title: '获取体力',
      content: '选择获取体力的方式：\n· 分享给好友 +1点\n· 观看广告 +3点',
      confirmText: '分享获取',
      cancelText: '观看广告',
      confirmColor: '#10B981',
      cancelColor: '#F59E0B',
      success: (res) => {
        if (res.confirm) {
          this.shareForEnergy();
        } else if (res.cancel) {
          this.watchAdForEnergy();
        }
      }
    });
  }

  // 新增：时间获取选择对话框
  showTimeAcquisitionDialog() {
    // 暂停计时器
    this.pauseTimer();

    wx.showModal({
      title: '获取时间',
      content: '选择获取时间的方式：\n· 分享给好友 +30秒\n· 观看广告 +60秒',
      confirmText: '分享获取',
      cancelText: '观看广告',
      confirmColor: '#10B981',
      cancelColor: '#F59E0B',
      success: (res) => {
        if (res.confirm) {
          this.shareForTime();
        } else if (res.cancel) {
          this.watchAdForTime();
        } else {
          // 用户取消或关闭弹窗，恢复计时器
          this.resumeTimer();
        }
      },
      fail: () => {
        // 弹窗显示失败，恢复计时器
        this.resumeTimer();
      }
    });
  }

  // 新增：暂停计时器的方法
  pauseTimer() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
      this.timerInterval = null;
      this.isTimerPaused = true;
      console.log('计时器已暂停');
    }
  }

  // 新增：恢复计时器的方法
  resumeTimer() {
    if (this.isTimerPaused && this.gameStarted) {
      this.startTimer();
      this.isTimerPaused = false;
      console.log('计时器已恢复');
    }
  }

  // 修改成功完成检查
  checkCompletion() {
    // 检查所有拼图块是否都在正确位置
    for (const tile of this.tiles) {
      if (tile.currentRow !== tile.correctRow || tile.currentCol !== tile.correctCol) {
        return false;
      }
    }

    // 停止计时器
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
      this.timerInterval = null;
    }

    return true;
  }

  // 页面销毁时清理计时器
  destroy() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
      this.timerInterval = null;
    }
  }

  showSuccess() {
    const usedTime = this.timeLimit - this.remainingTime;
    const minutes = Math.floor(usedTime / 60);
    const seconds = usedTime % 60;

    wx.showModal({
      title: '恭喜！',
      content: `你用了 ${this.steps} 步，${minutes}分${seconds}秒完成拼图！`,
      confirmText: '再玩一次',
      cancelText: '分享成绩',
      success: (res) => {
        if (res.confirm) {
          this.start();
        } else {
          // 分享成绩
          wx.shareAppMessage({
            title: `我在${this.gridSize}×${this.gridSize}拼图中用了${this.steps}步完成！`,
            imageUrl: 'images/share.png'
          });
        }
      }
    });
  }

  // 修改 backToMenu 方法，重置暂停状态
  backToMenu() {
    console.log('返回菜单');

    // 停止计时器
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
      this.timerInterval = null;
    }

    // 重置暂停状态
    this.isTimerPaused = false;

    // 重置游戏状态
    this.gameStarted = false;
    this.draggingTile = null;

    // 调用回调
    if (this.onBackToMenu) {
      this.onBackToMenu();
    }
  }

  restart() {
    this.start();
  }

  // 格式化时间显示 (MM:SS)
  formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }

  // 修改体力不足对话框，显示恢复时间
  // showNoEnergyDialog2() {
  //   const timeToNextRecovery = this.energyManager.getTimeToNextRecovery();
  //   const recoveryTime = this.energyManager.formatRecoveryTime(timeToNextRecovery);

  //   let content = '体力不足，无法开始游戏！';
  //   if (timeToNextRecovery > 0) {
  //     content += `\n${recoveryTime}后恢复1点体力`;
  //   }
  //   content += '\n观看广告可以立即获得体力。';

  //   wx.showModal({
  //     title: '体力不足',
  //     content: content,
  //     confirmText: '观看广告',
  //     cancelText: '取消',
  //     success: (res) => {
  //       if (res.confirm) {
  //         this.watchAdForEnergy();
  //       }
  //     }
  //   });
  // }

  // 修改原有的 watchAdForEnergy 方法
  watchAdForEnergy() {
    // 在实际应用中，这里应该调用微信广告API
    // 这里模拟广告回调
    console.log('模拟观看广告获取体力');

    // 模拟广告成功回调
    setTimeout(() => {
      this.energyManager.addEnergyFromAd(3);

      // 显示获得体力提示
      wx.showToast({
        title: `获得3点体力！`,
        icon: 'success',
        duration: 2000
      });

      // 刷新显示
      this.draw();

      // 如果有能量更新回调，调用它
      if (this.onEnergyUpdated) {
        this.onEnergyUpdated();
      }
    }, 1000);
  }

  // 修改 watchAdForEnergy 方法，保持一致性
  watchAdForEnergy() {
    // 在实际应用中，这里应该调用微信广告API
    // 这里模拟广告回调
    console.log('模拟观看广告');

    // 模拟广告成功回调
    setTimeout(() => {
      this.energyManager.addEnergyFromAd(3);

      // 显示获得体力提示
      wx.showToast({
        title: `获得3点体力！`,
        icon: 'success',
        duration: 2000
      });

      // 刷新显示
      this.draw();

      // 如果有能量更新回调，调用它
      if (this.onEnergyUpdated) {
        this.onEnergyUpdated();
      }
    }, 1000);
  }

  // 计算完成百分比
  getCompletionPercent() {
    let correctCount = 0;
    for (const tile of this.tiles) {
      if (tile.currentRow === tile.correctRow && tile.currentCol === tile.correctCol) {
        correctCount++;
      }
    }
    const totalTiles = this.gridSize * this.gridSize - 1; // 减去空白块
    return Math.round((correctCount / totalTiles) * 100);
  }

  // 修改 showEnergyDialog 方法
  showEnergyDialog() {
    const currentEnergy = this.energyManager.getCurrentEnergy();
    const maxEnergy = this.energyManager.maxEnergy;
    const timeToNextRecovery = this.energyManager.getTimeToNextRecovery();

    let content = `当前体力: ${currentEnergy}/${maxEnergy}`;

    if (currentEnergy < maxEnergy) {
      if (timeToNextRecovery > 0) {
        const recoveryTime = this.energyManager.formatRecoveryTime(timeToNextRecovery);
        content += `\n${recoveryTime}后恢复1点体力`;
      } else {
        content += '\n体力已恢复';
      }
    } else {
      content += '\n体力已满';
    }

    content += '\n\n获取更多体力方式：';
    content += '\n· 分享给好友 +1点';
    content += '\n· 观看广告 +3点';

    wx.showModal({
      title: '体力信息',
      content: content,
      confirmText: '分享获取',
      cancelText: '观看广告',
      confirmColor: '#10B981',
      cancelColor: '#F59E0B',
      success: (res) => {
        if (res.confirm) {
          this.shareForEnergy();
        } else if (res.cancel) {
          this.watchAdForEnergy();
        }
      }
    });
  }

  // 修改原有的 shareForEnergy 方法
  shareForEnergy() {
    // 调起分享
    wx.shareAppMessage({
      title: '这个拼图游戏超好玩！快来挑战你的大脑！🧩',
      imageUrl: 'images/share.png'
    });

    // 延迟5秒后获得体力
    setTimeout(() => {
      this.energyManager.addEnergyFromAd(1);
      wx.showToast({
        title: '获得1点体力！',
        icon: 'success',
        duration: 2000
      });

      // 刷新显示
      this.draw();

      // 如果有能量更新回调，调用它
      if (this.onEnergyUpdated) {
        this.onEnergyUpdated();
      }
    }, 5000);
  }

  // 修改原有的 watchAdForTime 方法
  watchAdForTime() {
    // 在实际应用中，这里应该调用微信广告API
    // 这里模拟广告回调
    console.log('模拟观看广告增加时间');

    // 模拟广告成功回调
    setTimeout(() => {
      // 增加60秒时间
      this.remainingTime += 60;

      // 显示获得时间提示
      wx.showToast({
        title: `获得60秒时间！`,
        icon: 'success',
        duration: 2000
      });

      // 恢复计时器
      this.resumeTimer();

      // 刷新显示
      this.draw();
    }, 1000);
  }

  // 新增：分享获取时间的方法
  shareForTime() {
    // 调起分享
    wx.shareAppMessage({
      title: '这个拼图游戏超好玩！快来挑战你的大脑！🧩',
      imageUrl: 'images/share.png'
    });

    // 延迟5秒后获得时间
    setTimeout(() => {
      // 增加30秒时间
      this.remainingTime += 30;

      // 显示获得时间提示
      wx.showToast({
        title: '获得30秒时间！',
        icon: 'success',
        duration: 2000
      });

      // 恢复计时器
      this.resumeTimer();

      // 刷新显示
      this.draw();
    }, 5000);
  }
}